package hhtc.jsjds.web;

import hhtc.jsjds.service.UploadService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author czh
 */
@Slf4j
@RestController
@RequestMapping("/upload")
public class UploadController {

    @Autowired
    private UploadService uploadService;

    private final Path rootLocation = Paths.get("storage");;
    /**
     * 上传图片功能
     * @param file
     * @return
     */
    @PostMapping("/image")
    public ResponseEntity<String> uploadImage(@RequestParam("file") MultipartFile file) {
        String url = this.uploadService.upload(file);
        if (StringUtils.isBlank(url)) {
            // url为空，证明上传失败
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
        // 返回200，并且携带url路径
        log.info("url ={}",url);
        return ResponseEntity.ok(url);
    }

    @GetMapping("/fetch/{key:.+}")
    public ResponseEntity<Resource> uploadImage(@PathVariable String key) {
        log.info("key={}",key);
        if (key == null) {
            return ResponseEntity.notFound().build();
        }
        if (key.contains("../")) {
            return ResponseEntity.badRequest().build();
        }
        String type = "image/jpeg";
        MediaType mediaType = MediaType.parseMediaType(type);

        Resource file = null;

        try {
            Path fileP = rootLocation.resolve(key);
            Resource resource = new UrlResource(fileP.toUri());
            if (resource.exists() || resource.isReadable()) {
                file = resource;
            } else {
                file = null;
            }
        } catch (MalformedURLException e) {
            file = null;
        }
        if (file == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok().contentType(mediaType).body(file);
    }


}
